home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-installer.exe / bin / codecs.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2014-12-31  |  33.9 KB  |  1,070 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. ''' codecs -- Python Codec Registry, API and helpers.
  5.  
  6.  
  7. Written by Marc-Andre Lemburg (mal@lemburg.com).
  8.  
  9. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  10.  
  11. '''
  12. import __builtin__
  13. import sys
  14.  
  15. try:
  16.     from _codecs import *
  17. except ImportError:
  18.     why = None
  19.     raise SystemError('Failed to load the builtin codecs: %s' % why)
  20.  
  21. __all__ = [
  22.     'register',
  23.     'lookup',
  24.     'open',
  25.     'EncodedFile',
  26.     'BOM',
  27.     'BOM_BE',
  28.     'BOM_LE',
  29.     'BOM32_BE',
  30.     'BOM32_LE',
  31.     'BOM64_BE',
  32.     'BOM64_LE',
  33.     'BOM_UTF8',
  34.     'BOM_UTF16',
  35.     'BOM_UTF16_LE',
  36.     'BOM_UTF16_BE',
  37.     'BOM_UTF32',
  38.     'BOM_UTF32_LE',
  39.     'BOM_UTF32_BE',
  40.     'strict_errors',
  41.     'ignore_errors',
  42.     'replace_errors',
  43.     'xmlcharrefreplace_errors',
  44.     'register_error',
  45.     'lookup_error']
  46. BOM_UTF8 = '\xef\xbb\xbf'
  47. BOM_LE = BOM_UTF16_LE = '\xff\xfe'
  48. BOM_BE = BOM_UTF16_BE = '\xfe\xff'
  49. BOM_UTF32_LE = '\xff\xfe\x00\x00'
  50. BOM_UTF32_BE = '\x00\x00\xfe\xff'
  51. if sys.byteorder == 'little':
  52.     BOM = BOM_UTF16 = BOM_UTF16_LE
  53.     BOM_UTF32 = BOM_UTF32_LE
  54. else:
  55.     BOM = BOM_UTF16 = BOM_UTF16_BE
  56.     BOM_UTF32 = BOM_UTF32_BE
  57. BOM32_LE = BOM_UTF16_LE
  58. BOM32_BE = BOM_UTF16_BE
  59. BOM64_LE = BOM_UTF32_LE
  60. BOM64_BE = BOM_UTF32_BE
  61.  
  62. class CodecInfo(tuple):
  63.     
  64.     def __new__(cls, encode, decode, streamreader = None, streamwriter = None, incrementalencoder = None, incrementaldecoder = None, name = None):
  65.         self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))
  66.         self.name = name
  67.         self.encode = encode
  68.         self.decode = decode
  69.         self.incrementalencoder = incrementalencoder
  70.         self.incrementaldecoder = incrementaldecoder
  71.         self.streamwriter = streamwriter
  72.         self.streamreader = streamreader
  73.         return self
  74.  
  75.     
  76.     def __repr__(self):
  77.         return '<%s.%s object for encoding %s at 0x%x>' % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
  78.  
  79.  
  80.  
  81. class Codec:
  82.     """ Defines the interface for stateless encoders/decoders.
  83.  
  84.         The .encode()/.decode() methods may use different error
  85.         handling schemes by providing the errors argument. These
  86.         string values are predefined:
  87.  
  88.          'strict' - raise a ValueError error (or a subclass)
  89.          'ignore' - ignore the character and continue with the next
  90.          'replace' - replace with a suitable replacement character;
  91.                     Python will use the official U+FFFD REPLACEMENT
  92.                     CHARACTER for the builtin Unicode codecs on
  93.                     decoding and '?' on encoding.
  94.          'xmlcharrefreplace' - Replace with the appropriate XML
  95.                                character reference (only for encoding).
  96.          'backslashreplace'  - Replace with backslashed escape sequences
  97.                                (only for encoding).
  98.  
  99.         The set of allowed values can be extended via register_error.
  100.  
  101.     """
  102.     
  103.     def encode(self, input, errors = 'strict'):
  104.         """ Encodes the object input and returns a tuple (output
  105.             object, length consumed).
  106.  
  107.             errors defines the error handling to apply. It defaults to
  108.             'strict' handling.
  109.  
  110.             The method may not store state in the Codec instance. Use
  111.             StreamCodec for codecs which have to keep state in order to
  112.             make encoding/decoding efficient.
  113.  
  114.             The encoder must be able to handle zero length input and
  115.             return an empty object of the output object type in this
  116.             situation.
  117.  
  118.         """
  119.         raise NotImplementedError
  120.  
  121.     
  122.     def decode(self, input, errors = 'strict'):
  123.         """ Decodes the object input and returns a tuple (output
  124.             object, length consumed).
  125.  
  126.             input must be an object which provides the bf_getreadbuf
  127.             buffer slot. Python strings, buffer objects and memory
  128.             mapped files are examples of objects providing this slot.
  129.  
  130.             errors defines the error handling to apply. It defaults to
  131.             'strict' handling.
  132.  
  133.             The method may not store state in the Codec instance. Use
  134.             StreamCodec for codecs which have to keep state in order to
  135.             make encoding/decoding efficient.
  136.  
  137.             The decoder must be able to handle zero length input and
  138.             return an empty object of the output object type in this
  139.             situation.
  140.  
  141.         """
  142.         raise NotImplementedError
  143.  
  144.  
  145.  
  146. class IncrementalEncoder(object):
  147.     '''
  148.     An IncrementalEncoder encodes an input in multiple steps. The input can be
  149.     passed piece by piece to the encode() method. The IncrementalEncoder remembers
  150.     the state of the Encoding process between calls to encode().
  151.     '''
  152.     
  153.     def __init__(self, errors = 'strict'):
  154.         '''
  155.         Creates an IncrementalEncoder instance.
  156.  
  157.         The IncrementalEncoder may use different error handling schemes by
  158.         providing the errors keyword argument. See the module docstring
  159.         for a list of possible values.
  160.         '''
  161.         self.errors = errors
  162.         self.buffer = ''
  163.  
  164.     
  165.     def encode(self, input, final = False):
  166.         '''
  167.         Encodes input and returns the resulting object.
  168.         '''
  169.         raise NotImplementedError
  170.  
  171.     
  172.     def reset(self):
  173.         '''
  174.         Resets the encoder to the initial state.
  175.         '''
  176.         pass
  177.  
  178.     
  179.     def getstate(self):
  180.         '''
  181.         Return the current state of the encoder.
  182.         '''
  183.         return 0
  184.  
  185.     
  186.     def setstate(self, state):
  187.         '''
  188.         Set the current state of the encoder. state must have been
  189.         returned by getstate().
  190.         '''
  191.         pass
  192.  
  193.  
  194.  
  195. class BufferedIncrementalEncoder(IncrementalEncoder):
  196.     '''
  197.     This subclass of IncrementalEncoder can be used as the baseclass for an
  198.     incremental encoder if the encoder must keep some of the output in a
  199.     buffer between calls to encode().
  200.     '''
  201.     
  202.     def __init__(self, errors = 'strict'):
  203.         IncrementalEncoder.__init__(self, errors)
  204.         self.buffer = ''
  205.  
  206.     
  207.     def _buffer_encode(self, input, errors, final):
  208.         raise NotImplementedError
  209.  
  210.     
  211.     def encode(self, input, final = False):
  212.         data = self.buffer + input
  213.         (result, consumed) = self._buffer_encode(data, self.errors, final)
  214.         self.buffer = data[consumed:]
  215.         return result
  216.  
  217.     
  218.     def reset(self):
  219.         IncrementalEncoder.reset(self)
  220.         self.buffer = ''
  221.  
  222.     
  223.     def getstate(self):
  224.         if not self.buffer:
  225.             pass
  226.         return 0
  227.  
  228.     
  229.     def setstate(self, state):
  230.         if not state:
  231.             pass
  232.         self.buffer = ''
  233.  
  234.  
  235.  
  236. class IncrementalDecoder(object):
  237.     '''
  238.     An IncrementalDecoder decodes an input in multiple steps. The input can be
  239.     passed piece by piece to the decode() method. The IncrementalDecoder
  240.     remembers the state of the decoding process between calls to decode().
  241.     '''
  242.     
  243.     def __init__(self, errors = 'strict'):
  244.         '''
  245.         Creates a IncrementalDecoder instance.
  246.  
  247.         The IncrementalDecoder may use different error handling schemes by
  248.         providing the errors keyword argument. See the module docstring
  249.         for a list of possible values.
  250.         '''
  251.         self.errors = errors
  252.  
  253.     
  254.     def decode(self, input, final = False):
  255.         '''
  256.         Decodes input and returns the resulting object.
  257.         '''
  258.         raise NotImplementedError
  259.  
  260.     
  261.     def reset(self):
  262.         '''
  263.         Resets the decoder to the initial state.
  264.         '''
  265.         pass
  266.  
  267.     
  268.     def getstate(self):
  269.         '''
  270.         Return the current state of the decoder.
  271.  
  272.         This must be a (buffered_input, additional_state_info) tuple.
  273.         buffered_input must be a bytes object containing bytes that
  274.         were passed to decode() that have not yet been converted.
  275.         additional_state_info must be a non-negative integer
  276.         representing the state of the decoder WITHOUT yet having
  277.         processed the contents of buffered_input.  In the initial state
  278.         and after reset(), getstate() must return (b"", 0).
  279.         '''
  280.         return ('', 0)
  281.  
  282.     
  283.     def setstate(self, state):
  284.         '''
  285.         Set the current state of the decoder.
  286.  
  287.         state must have been returned by getstate().  The effect of
  288.         setstate((b"", 0)) must be equivalent to reset().
  289.         '''
  290.         pass
  291.  
  292.  
  293.  
  294. class BufferedIncrementalDecoder(IncrementalDecoder):
  295.     '''
  296.     This subclass of IncrementalDecoder can be used as the baseclass for an
  297.     incremental decoder if the decoder must be able to handle incomplete byte
  298.     sequences.
  299.     '''
  300.     
  301.     def __init__(self, errors = 'strict'):
  302.         IncrementalDecoder.__init__(self, errors)
  303.         self.buffer = ''
  304.  
  305.     
  306.     def _buffer_decode(self, input, errors, final):
  307.         raise NotImplementedError
  308.  
  309.     
  310.     def decode(self, input, final = False):
  311.         data = self.buffer + input
  312.         (result, consumed) = self._buffer_decode(data, self.errors, final)
  313.         self.buffer = data[consumed:]
  314.         return result
  315.  
  316.     
  317.     def reset(self):
  318.         IncrementalDecoder.reset(self)
  319.         self.buffer = ''
  320.  
  321.     
  322.     def getstate(self):
  323.         return (self.buffer, 0)
  324.  
  325.     
  326.     def setstate(self, state):
  327.         self.buffer = state[0]
  328.  
  329.  
  330.  
  331. class StreamWriter(Codec):
  332.     
  333.     def __init__(self, stream, errors = 'strict'):
  334.         """ Creates a StreamWriter instance.
  335.  
  336.             stream must be a file-like object open for writing
  337.             (binary) data.
  338.  
  339.             The StreamWriter may use different error handling
  340.             schemes by providing the errors keyword argument. These
  341.             parameters are predefined:
  342.  
  343.              'strict' - raise a ValueError (or a subclass)
  344.              'ignore' - ignore the character and continue with the next
  345.              'replace'- replace with a suitable replacement character
  346.              'xmlcharrefreplace' - Replace with the appropriate XML
  347.                                    character reference.
  348.              'backslashreplace'  - Replace with backslashed escape
  349.                                    sequences (only for encoding).
  350.  
  351.             The set of allowed parameter values can be extended via
  352.             register_error.
  353.         """
  354.         self.stream = stream
  355.         self.errors = errors
  356.  
  357.     
  358.     def write(self, object):
  359.         """ Writes the object's contents encoded to self.stream.
  360.         """
  361.         (data, consumed) = self.encode(object, self.errors)
  362.         self.stream.write(data)
  363.  
  364.     
  365.     def writelines(self, list):
  366.         ''' Writes the concatenated list of strings to the stream
  367.             using .write().
  368.         '''
  369.         self.write(''.join(list))
  370.  
  371.     
  372.     def reset(self):
  373.         ''' Flushes and resets the codec buffers used for keeping state.
  374.  
  375.             Calling this method should ensure that the data on the
  376.             output is put into a clean state, that allows appending
  377.             of new fresh data without having to rescan the whole
  378.             stream to recover state.
  379.  
  380.         '''
  381.         pass
  382.  
  383.     
  384.     def seek(self, offset, whence = 0):
  385.         self.stream.seek(offset, whence)
  386.         if whence == 0 and offset == 0:
  387.             self.reset()
  388.  
  389.     
  390.     def __getattr__(self, name, getattr = getattr):
  391.         ''' Inherit all other methods from the underlying stream.
  392.         '''
  393.         return getattr(self.stream, name)
  394.  
  395.     
  396.     def __enter__(self):
  397.         return self
  398.  
  399.     
  400.     def __exit__(self, type, value, tb):
  401.         self.stream.close()
  402.  
  403.  
  404.  
  405. class StreamReader(Codec):
  406.     
  407.     def __init__(self, stream, errors = 'strict'):
  408.         """ Creates a StreamReader instance.
  409.  
  410.             stream must be a file-like object open for reading
  411.             (binary) data.
  412.  
  413.             The StreamReader may use different error handling
  414.             schemes by providing the errors keyword argument. These
  415.             parameters are predefined:
  416.  
  417.              'strict' - raise a ValueError (or a subclass)
  418.              'ignore' - ignore the character and continue with the next
  419.              'replace'- replace with a suitable replacement character;
  420.  
  421.             The set of allowed parameter values can be extended via
  422.             register_error.
  423.         """
  424.         self.stream = stream
  425.         self.errors = errors
  426.         self.bytebuffer = ''
  427.         self.charbuffer = ''
  428.         self.linebuffer = None
  429.  
  430.     
  431.     def decode(self, input, errors = 'strict'):
  432.         raise NotImplementedError
  433.  
  434.     
  435.     def read(self, size = -1, chars = -1, firstline = False):
  436.         ''' Decodes data from the stream self.stream and returns the
  437.             resulting object.
  438.  
  439.             chars indicates the number of characters to read from the
  440.             stream. read() will never return more than chars
  441.             characters, but it might return less, if there are not enough
  442.             characters available.
  443.  
  444.             size indicates the approximate maximum number of bytes to
  445.             read from the stream for decoding purposes. The decoder
  446.             can modify this setting as appropriate. The default value
  447.             -1 indicates to read and decode as much as possible.  size
  448.             is intended to prevent having to decode huge files in one
  449.             step.
  450.  
  451.             If firstline is true, and a UnicodeDecodeError happens
  452.             after the first line terminator in the input only the first line
  453.             will be returned, the rest of the input will be kept until the
  454.             next call to read().
  455.  
  456.             The method should use a greedy read strategy meaning that
  457.             it should read as much data as is allowed within the
  458.             definition of the encoding and the given size, e.g.  if
  459.             optional encoding endings or state markers are available
  460.             on the stream, these should be read too.
  461.         '''
  462.         if self.linebuffer:
  463.             self.charbuffer = ''.join(self.linebuffer)
  464.             self.linebuffer = None
  465.         while True:
  466.             if chars < 0:
  467.                 if size < 0 or self.charbuffer:
  468.                     break
  469.                 
  470.             elif len(self.charbuffer) >= size:
  471.                 break
  472.             
  473.         if len(self.charbuffer) >= chars:
  474.             break
  475.         if size < 0:
  476.             newdata = self.stream.read()
  477.         else:
  478.             newdata = self.stream.read(size)
  479.         data = self.bytebuffer + newdata
  480.         
  481.         try:
  482.             (newchars, decodedbytes) = self.decode(data, self.errors)
  483.         except UnicodeDecodeError:
  484.             exc = None
  485.             if firstline:
  486.                 (newchars, decodedbytes) = self.decode(data[:exc.start], self.errors)
  487.                 lines = newchars.splitlines(True)
  488.                 if len(lines) <= 1:
  489.                     raise 
  490.             else:
  491.                 raise 
  492.  
  493.         self.bytebuffer = data[decodedbytes:]
  494.         self.charbuffer += newchars
  495.         if not newdata:
  496.             break
  497.             continue
  498.         return result
  499.  
  500.     
  501.     def readline(self, size = None, keepends = True):
  502.         ''' Read one line from the input stream and return the
  503.             decoded data.
  504.  
  505.             size, if given, is passed as size argument to the
  506.             read() method.
  507.  
  508.         '''
  509.         if self.linebuffer:
  510.             line = self.linebuffer[0]
  511.             del self.linebuffer[0]
  512.             if len(self.linebuffer) == 1:
  513.                 self.charbuffer = self.linebuffer[0]
  514.                 self.linebuffer = None
  515.             if not keepends:
  516.                 line = line.splitlines(False)[0]
  517.             return line
  518.         if not None:
  519.             pass
  520.         readsize = 72
  521.         line = ''
  522.         while True:
  523.             data = self.read(readsize, firstline = True)
  524.             if data and data.endswith('\r'):
  525.                 data += self.read(size = 1, chars = 1)
  526.             
  527.         line += data
  528.         lines = line.splitlines(True)
  529.         if lines:
  530.             if len(lines) > 1:
  531.                 line = lines[0]
  532.                 del lines[0]
  533.                 if len(lines) > 1:
  534.                     lines[-1] += self.charbuffer
  535.                     self.linebuffer = lines
  536.                     self.charbuffer = None
  537.                 else:
  538.                     self.charbuffer = lines[0] + self.charbuffer
  539.                 if not keepends:
  540.                     line = line.splitlines(False)[0]
  541.                 break
  542.             line0withend = lines[0]
  543.             line0withoutend = lines[0].splitlines(False)[0]
  544.             if line0withend != line0withoutend:
  545.                 self.charbuffer = ''.join(lines[1:]) + self.charbuffer
  546.                 if keepends:
  547.                     line = line0withend
  548.                 else:
  549.                     line = line0withoutend
  550.                 break
  551.             
  552.         if not data or size is not None:
  553.             if line and not keepends:
  554.                 line = line.splitlines(False)[0]
  555.             break
  556.         if readsize < 8000:
  557.             readsize *= 2
  558.             continue
  559.         return line
  560.  
  561.     
  562.     def readlines(self, sizehint = None, keepends = True):
  563.         """ Read all lines available on the input stream
  564.             and return them as list of lines.
  565.  
  566.             Line breaks are implemented using the codec's decoder
  567.             method and are included in the list entries.
  568.  
  569.             sizehint, if given, is ignored since there is no efficient
  570.             way to finding the true end-of-line.
  571.  
  572.         """
  573.         data = self.read()
  574.         return data.splitlines(keepends)
  575.  
  576.     
  577.     def reset(self):
  578.         ''' Resets the codec buffers used for keeping state.
  579.  
  580.             Note that no stream repositioning should take place.
  581.             This method is primarily intended to be able to recover
  582.             from decoding errors.
  583.  
  584.         '''
  585.         self.bytebuffer = ''
  586.         self.charbuffer = u''
  587.         self.linebuffer = None
  588.  
  589.     
  590.     def seek(self, offset, whence = 0):
  591.         """ Set the input stream's current position.
  592.  
  593.             Resets the codec buffers used for keeping state.
  594.         """
  595.         self.stream.seek(offset, whence)
  596.         self.reset()
  597.  
  598.     
  599.     def next(self):
  600.         ''' Return the next decoded line from the input stream.'''
  601.         line = self.readline()
  602.         if line:
  603.             return line
  604.         raise None
  605.  
  606.     
  607.     def __iter__(self):
  608.         return self
  609.  
  610.     
  611.     def __getattr__(self, name, getattr = getattr):
  612.         ''' Inherit all other methods from the underlying stream.
  613.         '''
  614.         return getattr(self.stream, name)
  615.  
  616.     
  617.     def __enter__(self):
  618.         return self
  619.  
  620.     
  621.     def __exit__(self, type, value, tb):
  622.         self.stream.close()
  623.  
  624.  
  625.  
  626. class StreamReaderWriter:
  627.     ''' StreamReaderWriter instances allow wrapping streams which
  628.         work in both read and write modes.
  629.  
  630.         The design is such that one can use the factory functions
  631.         returned by the codec.lookup() function to construct the
  632.         instance.
  633.  
  634.     '''
  635.     encoding = 'unknown'
  636.     
  637.     def __init__(self, stream, Reader, Writer, errors = 'strict'):
  638.         ''' Creates a StreamReaderWriter instance.
  639.  
  640.             stream must be a Stream-like object.
  641.  
  642.             Reader, Writer must be factory functions or classes
  643.             providing the StreamReader, StreamWriter interface resp.
  644.  
  645.             Error handling is done in the same way as defined for the
  646.             StreamWriter/Readers.
  647.  
  648.         '''
  649.         self.stream = stream
  650.         self.reader = Reader(stream, errors)
  651.         self.writer = Writer(stream, errors)
  652.         self.errors = errors
  653.  
  654.     
  655.     def read(self, size = -1):
  656.         return self.reader.read(size)
  657.  
  658.     
  659.     def readline(self, size = None):
  660.         return self.reader.readline(size)
  661.  
  662.     
  663.     def readlines(self, sizehint = None):
  664.         return self.reader.readlines(sizehint)
  665.  
  666.     
  667.     def next(self):
  668.         ''' Return the next decoded line from the input stream.'''
  669.         return self.reader.next()
  670.  
  671.     
  672.     def __iter__(self):
  673.         return self
  674.  
  675.     
  676.     def write(self, data):
  677.         return self.writer.write(data)
  678.  
  679.     
  680.     def writelines(self, list):
  681.         return self.writer.writelines(list)
  682.  
  683.     
  684.     def reset(self):
  685.         self.reader.reset()
  686.         self.writer.reset()
  687.  
  688.     
  689.     def seek(self, offset, whence = 0):
  690.         self.stream.seek(offset, whence)
  691.         self.reader.reset()
  692.         if whence == 0 and offset == 0:
  693.             self.writer.reset()
  694.  
  695.     
  696.     def __getattr__(self, name, getattr = getattr):
  697.         ''' Inherit all other methods from the underlying stream.
  698.         '''
  699.         return getattr(self.stream, name)
  700.  
  701.     
  702.     def __enter__(self):
  703.         return self
  704.  
  705.     
  706.     def __exit__(self, type, value, tb):
  707.         self.stream.close()
  708.  
  709.  
  710.  
  711. class StreamRecoder:
  712.     ''' StreamRecoder instances provide a frontend - backend
  713.         view of encoding data.
  714.  
  715.         They use the complete set of APIs returned by the
  716.         codecs.lookup() function to implement their task.
  717.  
  718.         Data written to the stream is first decoded into an
  719.         intermediate format (which is dependent on the given codec
  720.         combination) and then written to the stream using an instance
  721.         of the provided Writer class.
  722.  
  723.         In the other direction, data is read from the stream using a
  724.         Reader instance and then return encoded data to the caller.
  725.  
  726.     '''
  727.     data_encoding = 'unknown'
  728.     file_encoding = 'unknown'
  729.     
  730.     def __init__(self, stream, encode, decode, Reader, Writer, errors = 'strict'):
  731.         ''' Creates a StreamRecoder instance which implements a two-way
  732.             conversion: encode and decode work on the frontend (the
  733.             input to .read() and output of .write()) while
  734.             Reader and Writer work on the backend (reading and
  735.             writing to the stream).
  736.  
  737.             You can use these objects to do transparent direct
  738.             recodings from e.g. latin-1 to utf-8 and back.
  739.  
  740.             stream must be a file-like object.
  741.  
  742.             encode, decode must adhere to the Codec interface, Reader,
  743.             Writer must be factory functions or classes providing the
  744.             StreamReader, StreamWriter interface resp.
  745.  
  746.             encode and decode are needed for the frontend translation,
  747.             Reader and Writer for the backend translation. Unicode is
  748.             used as intermediate encoding.
  749.  
  750.             Error handling is done in the same way as defined for the
  751.             StreamWriter/Readers.
  752.  
  753.         '''
  754.         self.stream = stream
  755.         self.encode = encode
  756.         self.decode = decode
  757.         self.reader = Reader(stream, errors)
  758.         self.writer = Writer(stream, errors)
  759.         self.errors = errors
  760.  
  761.     
  762.     def read(self, size = -1):
  763.         data = self.reader.read(size)
  764.         (data, bytesencoded) = self.encode(data, self.errors)
  765.         return data
  766.  
  767.     
  768.     def readline(self, size = None):
  769.         if size is None:
  770.             data = self.reader.readline()
  771.         else:
  772.             data = self.reader.readline(size)
  773.         (data, bytesencoded) = self.encode(data, self.errors)
  774.         return data
  775.  
  776.     
  777.     def readlines(self, sizehint = None):
  778.         data = self.reader.read()
  779.         (data, bytesencoded) = self.encode(data, self.errors)
  780.         return data.splitlines(1)
  781.  
  782.     
  783.     def next(self):
  784.         ''' Return the next decoded line from the input stream.'''
  785.         data = self.reader.next()
  786.         (data, bytesencoded) = self.encode(data, self.errors)
  787.         return data
  788.  
  789.     
  790.     def __iter__(self):
  791.         return self
  792.  
  793.     
  794.     def write(self, data):
  795.         (data, bytesdecoded) = self.decode(data, self.errors)
  796.         return self.writer.write(data)
  797.  
  798.     
  799.     def writelines(self, list):
  800.         data = ''.join(list)
  801.         (data, bytesdecoded) = self.decode(data, self.errors)
  802.         return self.writer.write(data)
  803.  
  804.     
  805.     def reset(self):
  806.         self.reader.reset()
  807.         self.writer.reset()
  808.  
  809.     
  810.     def __getattr__(self, name, getattr = getattr):
  811.         ''' Inherit all other methods from the underlying stream.
  812.         '''
  813.         return getattr(self.stream, name)
  814.  
  815.     
  816.     def __enter__(self):
  817.         return self
  818.  
  819.     
  820.     def __exit__(self, type, value, tb):
  821.         self.stream.close()
  822.  
  823.  
  824.  
  825. def open(filename, mode = 'rb', encoding = None, errors = 'strict', buffering = 1):
  826.     """ Open an encoded file using the given mode and return
  827.         a wrapped version providing transparent encoding/decoding.
  828.  
  829.         Note: The wrapped version will only accept the object format
  830.         defined by the codecs, i.e. Unicode objects for most builtin
  831.         codecs. Output is also codec dependent and will usually be
  832.         Unicode as well.
  833.  
  834.         Files are always opened in binary mode, even if no binary mode
  835.         was specified. This is done to avoid data loss due to encodings
  836.         using 8-bit values. The default file mode is 'rb' meaning to
  837.         open the file in binary read mode.
  838.  
  839.         encoding specifies the encoding which is to be used for the
  840.         file.
  841.  
  842.         errors may be given to define the error handling. It defaults
  843.         to 'strict' which causes ValueErrors to be raised in case an
  844.         encoding error occurs.
  845.  
  846.         buffering has the same meaning as for the builtin open() API.
  847.         It defaults to line buffered.
  848.  
  849.         The returned wrapped file object provides an extra attribute
  850.         .encoding which allows querying the used encoding. This
  851.         attribute is only available if an encoding was specified as
  852.         parameter.
  853.  
  854.     """
  855.     if encoding is not None:
  856.         if 'U' in mode:
  857.             mode = mode.strip().replace('U', '')
  858.             if mode[:1] not in set('rwa'):
  859.                 mode = 'r' + mode
  860.             
  861.         if 'b' not in mode:
  862.             mode = mode + 'b'
  863.         
  864.     file = __builtin__.open(filename, mode, buffering)
  865.     if encoding is None:
  866.         return file
  867.     info = None(encoding)
  868.     srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
  869.     srw.encoding = encoding
  870.     return srw
  871.  
  872.  
  873. def EncodedFile(file, data_encoding, file_encoding = None, errors = 'strict'):
  874.     """ Return a wrapped version of file which provides transparent
  875.         encoding translation.
  876.  
  877.         Strings written to the wrapped file are interpreted according
  878.         to the given data_encoding and then written to the original
  879.         file as string using file_encoding. The intermediate encoding
  880.         will usually be Unicode but depends on the specified codecs.
  881.  
  882.         Strings are read from the file using file_encoding and then
  883.         passed back to the caller as string using data_encoding.
  884.  
  885.         If file_encoding is not given, it defaults to data_encoding.
  886.  
  887.         errors may be given to define the error handling. It defaults
  888.         to 'strict' which causes ValueErrors to be raised in case an
  889.         encoding error occurs.
  890.  
  891.         The returned wrapped file object provides two extra attributes
  892.         .data_encoding and .file_encoding which reflect the given
  893.         parameters of the same name. The attributes can be used for
  894.         introspection by Python programs.
  895.  
  896.     """
  897.     if file_encoding is None:
  898.         file_encoding = data_encoding
  899.     data_info = lookup(data_encoding)
  900.     file_info = lookup(file_encoding)
  901.     sr = StreamRecoder(file, data_info.encode, data_info.decode, file_info.streamreader, file_info.streamwriter, errors)
  902.     sr.data_encoding = data_encoding
  903.     sr.file_encoding = file_encoding
  904.     return sr
  905.  
  906.  
  907. def getencoder(encoding):
  908.     ''' Lookup up the codec for the given encoding and return
  909.         its encoder function.
  910.  
  911.         Raises a LookupError in case the encoding cannot be found.
  912.  
  913.     '''
  914.     return lookup(encoding).encode
  915.  
  916.  
  917. def getdecoder(encoding):
  918.     ''' Lookup up the codec for the given encoding and return
  919.         its decoder function.
  920.  
  921.         Raises a LookupError in case the encoding cannot be found.
  922.  
  923.     '''
  924.     return lookup(encoding).decode
  925.  
  926.  
  927. def getincrementalencoder(encoding):
  928.     """ Lookup up the codec for the given encoding and return
  929.         its IncrementalEncoder class or factory function.
  930.  
  931.         Raises a LookupError in case the encoding cannot be found
  932.         or the codecs doesn't provide an incremental encoder.
  933.  
  934.     """
  935.     encoder = lookup(encoding).incrementalencoder
  936.     if encoder is None:
  937.         raise LookupError(encoding)
  938.     return encoder
  939.  
  940.  
  941. def getincrementaldecoder(encoding):
  942.     """ Lookup up the codec for the given encoding and return
  943.         its IncrementalDecoder class or factory function.
  944.  
  945.         Raises a LookupError in case the encoding cannot be found
  946.         or the codecs doesn't provide an incremental decoder.
  947.  
  948.     """
  949.     decoder = lookup(encoding).incrementaldecoder
  950.     if decoder is None:
  951.         raise LookupError(encoding)
  952.     return decoder
  953.  
  954.  
  955. def getreader(encoding):
  956.     ''' Lookup up the codec for the given encoding and return
  957.         its StreamReader class or factory function.
  958.  
  959.         Raises a LookupError in case the encoding cannot be found.
  960.  
  961.     '''
  962.     return lookup(encoding).streamreader
  963.  
  964.  
  965. def getwriter(encoding):
  966.     ''' Lookup up the codec for the given encoding and return
  967.         its StreamWriter class or factory function.
  968.  
  969.         Raises a LookupError in case the encoding cannot be found.
  970.  
  971.     '''
  972.     return lookup(encoding).streamwriter
  973.  
  974.  
  975. def iterencode(iterator, encoding, errors = 'strict', **kwargs):
  976.     '''
  977.     Encoding iterator.
  978.  
  979.     Encodes the input strings from the iterator using a IncrementalEncoder.
  980.  
  981.     errors and kwargs are passed through to the IncrementalEncoder
  982.     constructor.
  983.     '''
  984.     encoder = getincrementalencoder(encoding)(errors, **kwargs)
  985.     for input in iterator:
  986.         output = encoder.encode(input)
  987.         if output:
  988.             yield output
  989.             continue
  990.     output = encoder.encode('', True)
  991.     if output:
  992.         yield output
  993.  
  994.  
  995. def iterdecode(iterator, encoding, errors = 'strict', **kwargs):
  996.     '''
  997.     Decoding iterator.
  998.  
  999.     Decodes the input strings from the iterator using a IncrementalDecoder.
  1000.  
  1001.     errors and kwargs are passed through to the IncrementalDecoder
  1002.     constructor.
  1003.     '''
  1004.     decoder = getincrementaldecoder(encoding)(errors, **kwargs)
  1005.     for input in iterator:
  1006.         output = decoder.decode(input)
  1007.         if output:
  1008.             yield output
  1009.             continue
  1010.     output = decoder.decode('', True)
  1011.     if output:
  1012.         yield output
  1013.  
  1014.  
  1015. def make_identity_dict(rng):
  1016.     ''' make_identity_dict(rng) -> dict
  1017.  
  1018.         Return a dictionary where elements of the rng sequence are
  1019.         mapped to themselves.
  1020.  
  1021.     '''
  1022.     res = { }
  1023.     for i in rng:
  1024.         res[i] = i
  1025.     
  1026.     return res
  1027.  
  1028.  
  1029. def make_encoding_map(decoding_map):
  1030.     ''' Creates an encoding map from a decoding map.
  1031.  
  1032.         If a target mapping in the decoding map occurs multiple
  1033.         times, then that target is mapped to None (undefined mapping),
  1034.         causing an exception when encountered by the charmap codec
  1035.         during translation.
  1036.  
  1037.         One example where this happens is cp875.py which decodes
  1038.         multiple character to \\u001a.
  1039.  
  1040.     '''
  1041.     m = { }
  1042.     for k, v in decoding_map.items():
  1043.         if v not in m:
  1044.             m[v] = k
  1045.             continue
  1046.         m[v] = None
  1047.     
  1048.     return m
  1049.  
  1050.  
  1051. try:
  1052.     strict_errors = lookup_error('strict')
  1053.     ignore_errors = lookup_error('ignore')
  1054.     replace_errors = lookup_error('replace')
  1055.     xmlcharrefreplace_errors = lookup_error('xmlcharrefreplace')
  1056.     backslashreplace_errors = lookup_error('backslashreplace')
  1057. except LookupError:
  1058.     strict_errors = None
  1059.     ignore_errors = None
  1060.     replace_errors = None
  1061.     xmlcharrefreplace_errors = None
  1062.     backslashreplace_errors = None
  1063.  
  1064. _false = 0
  1065. if _false:
  1066.     import encodings
  1067. if __name__ == '__main__':
  1068.     sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  1069.     sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
  1070.